package com.cloud.mall.conf.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: 梁二东
 * @Date: 2024/12/8 14:06
 * @Description:
 **/
@Component
@Slf4j
public class MetricsGlobalFilter implements GlobalFilter, Ordered {

    private static final String BEGIN_TIME = "begin_time";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        exchange.getAttributes().put(BEGIN_TIME, System.currentTimeMillis());

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long beginTime = exchange.getAttribute(BEGIN_TIME);
            Long runtime = System.currentTimeMillis() - beginTime;
            if (beginTime != null) {
//                log.info("访问接口主机:" + request.getURI().getHost());
//                log.info("访问接口端口:" + request.getURI().getPort());
                log.info("访问接口uri:" + request.getURI());
                log.info("访问接口时长:" + runtime + "毫秒");
            }
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
